package com.yyge.controller.mobile.addressbook;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yyge.common.controller.BaseController;
import com.yyge.common.enums.AckCode;
import com.yyge.common.util.WaimaiThreadLocal;
import com.yyge.common.vo.resp.PageResp;
import com.yyge.common.vo.resp.R;
import com.yyge.controller.mobile.addressbook.req.AddressBookEditReq;
import com.yyge.controller.mobile.addressbook.req.AddressBookReq;
import com.yyge.controller.mobile.addressbook.resp.AddressBookResp;
import com.yyge.controller.mobile.login.resp.MobileLoginResp;
import com.yyge.controller.mobile.mapstruct.AddressBookConvert;
import com.yyge.entity.AddressBook;
import com.yyge.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Api(value = "移动端-收获地址API")
@RequestMapping(value = "/mobile/addressbook")
@RestController
public class MobileAddressBookController extends BaseController<AddressBook,AddressBookResp> {

    public MobileAddressBookController() {
        this.converter = AddressBookConvert.class;
    }

    @Autowired
    AddressBookService addressBookService;

    @GetMapping("/data")
    public R<List<AddressBook>> getAddressBook(){
        MobileLoginResp user = WaimaiThreadLocal.mobileLoginThreadLocal.get();
        AddressBook book = new AddressBook();
        book.setUserId(Long.parseLong(user.getId()+""));
        QueryWrapper<AddressBook> wrapper=new QueryWrapper<>(book);
        wrapper.eq("is_deleted","0");

//        wrapper.orderByDesc("is_default","1");
//        wrapper.orderByDesc("create_time");
        List<AddressBook> list = addressBookService.list(wrapper);
        PageResp<AddressBookResp> pageResp=new PageResp<>();

        return R.okHasData(list);
    }

    @PostMapping
    @Transactional(rollbackFor = Exception.class) /*开启事务*/
    public R addAddressBook(@RequestBody AddressBookReq req) throws Exception {
        MobileLoginResp user = WaimaiThreadLocal.mobileLoginThreadLocal.get();
        AddressBook address = getEntity(req);
        System.out.println("------------");
        System.out.println(address);
        long count = addressBookService.count(new QueryWrapper<>(address));

        System.out.println("判断数据库中是否含有");
        System.out.println(count);
        if(count > 0){
            return  R.build(AckCode.EXISTS_DEFAULT_ADDRESS);
        }

        address.setUserId(Long.parseLong(user.getId()+""));
        address.setUpdateBy(user.getUserName());
//        address.setCreateBy(Long.parseLong(user.getId()+""));
//        address.setCreateTime(new Date());
        address.setUpdateTime(new Date());
        address.setIsDefault("1");
        System.out.println("当前数据...");
        System.out.println(address);
        /*将数据库所有的内容设置为非默认地址*/
        UpdateWrapper<AddressBook> updateWrapper = new UpdateWrapper();
        updateWrapper.set("is_default",0);
        updateWrapper.eq("user_id",user.getId());
        boolean update = addressBookService.update(updateWrapper);

        boolean save = false;
        if(update){
            save = addressBookService.save(address);
        }

        System.out.println(R.ok());

     return save ?R.ok(save):R.build(AckCode.FAIL);
    }


    @GetMapping(value = "/default/{id}")
    @Transactional/*添加事务*/
    public R defaultAddressBook(@PathVariable("id") String id){
        MobileLoginResp user = WaimaiThreadLocal.mobileLoginThreadLocal.get();

        /*将数据库所有的内容设置为非默认地址*/
        UpdateWrapper<AddressBook> updateWrapper = new UpdateWrapper();
        updateWrapper.set("is_default",0);
        updateWrapper.eq("user_id",user.getId());
        boolean update = addressBookService.update(updateWrapper);

        UpdateWrapper<AddressBook> wrapper = new UpdateWrapper();
        wrapper.eq("id",id);
        wrapper.set("is_default",1);

        boolean isDefault=false;
        if(update){
            isDefault = addressBookService.update(wrapper);
        }

     return isDefault ?R.ok(isDefault):R.build(AckCode.FAIL);
    }


    @GetMapping(value = "{id}")
    public R getByAddressBook(@PathVariable("id") String id) throws Exception {
       AddressBook byId = addressBookService.getById(id);
       return R.okHasData(getResp(byId));
    }

    /**
     * 修改地址信息
     * @param req
     * @return
     */
    @PutMapping
    @Transactional(rollbackFor = Exception.class)/*添加事务*/
    public R updataAddressBook(@RequestBody AddressBookEditReq req) {
        MobileLoginResp user = WaimaiThreadLocal.mobileLoginThreadLocal.get();
        //如果当前是默认的收货地址 则 需要将数据库其他的数据改为非默认地址
        System.out.println("111111111111111111");
        System.out.println(req.getIsDefault());
        if(req.getIsDefault().equals("1")){
            UpdateWrapper<AddressBook> updateWrapper=new UpdateWrapper();
            updateWrapper.eq("user_id",user.getId());
            updateWrapper.set("is_default",0);
        }

        AddressBook convert = AddressBookConvert.MAPPER.convert(req);
        convert.setUpdateTime(new Date());
        convert.setUpdateBy(user.getUserName());
        System.out.println("转换之后的对象*--------");
        System.out.println(convert);
        boolean modiffy = addressBookService.updateById(convert);
     return modiffy?R.ok():R.build(AckCode.FAIL);
    }


    @ApiOperation(value = "获取用户默认收货地址")
    @GetMapping(value = "/default")
    public R<AddressBookResp> defaultAddress() throws Exception {
        Integer userId = WaimaiThreadLocal.mobileLoginThreadLocal.get().getId();

        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,userId);
        //sys_normal_disable
        queryWrapper.eq(AddressBook::getIsDeleted,"0");
        //sys_is_frame
        queryWrapper.eq(AddressBook::getIsDefault, "1");
        AddressBook db = this.addressBookService.getOne(queryWrapper);
        if(Objects.isNull(db)){
            return R.build(AckCode.NOT_FOUND_DATA);
        }

        //getResp 已经将类型转换为了Resp
        return R.okHasData(getResp(db));
    }
}
